<?php


namespace BoojasrFramework\DependencyInjection\Compiler;


use BoojasrFramework\Kernel;
use BoojasrFramework\Loader\AnnotationDirectoryLoader;
use BoojasrFramework\Loader\AnnotationRouteAnnotationClassLoader;
use BoojasrFramework\ServicesContainer\ContainerBuilder;
use BoojasrFramework\Service\RouteManageService;
use BoojasrFramework\ServicesContainer\DependencyInjection\Compiler\CompilerPassInterface;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class RoutePass implements CompilerPassInterface
{

    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition("route_manage")){
            return ;
        }
        $routes = Kernel::getRouteConfigs();
        /** @var RouteManageService $routeManage */
        $routeManage = $container->get("route_manage");

        $collection = new RouteCollection();
        // 扫描路由
        $config = Kernel::getConfig();
        if (isset($config["controllers"]) && isset($config["controllers"]["resource"])){
            $controllerResource = $config["controllers"]["resource"];
            $fileLocator = new FileLocator(); // 文件加载类
            $sar = new AnnotationReader();// 注解渲染类
            $sar->addGlobalIgnoredName("endlink"); // 添加忽略 @endlink 注解，在扫描@endlink时会遇到异常
            $annotationClassLoader = new AnnotationRouteAnnotationClassLoader($sar); // 控制器注解路由加载配置类
            $annotationDirectoryLoader = new AnnotationDirectoryLoader($fileLocator,$annotationClassLoader); // 注解目录加载类
            //按顺序加载对应的路由
            if (is_dir($controllerResource)) {
                $annotationRouteCollection = $annotationDirectoryLoader->load($controllerResource); // 扫描注解路由到RouteCollection
                $collection->addCollection($annotationRouteCollection);//将路由添加到RouteCollection
                $routes = array_merge($routes,$collection->all());
            }
        }
        foreach ($routes as $name=>$route){
            if(!$route instanceof Route){
                continue;
            }
            $routeManage->addRoute($name,$route);
        }
    }
}